package com.yuanqi.dz.dc.util;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.SocketException;


import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

import pnbclient.util.PnbLogFactory;
import pnblog.PnbLogging;

public class FtpUtil {
	public static final PnbLogging LOG = PnbLogFactory.getLogger("DZ_EXT_LOG");


	private FTPClient ftpclient =null; 

	private String address;
	private int port;
	private String username;
	private String pwd;
	private String remotepath;


	public FtpUtil(String address, int port,
			String username, String pwd, String remotepath) {
		super();

		this.address = address;
		this.port = port;
		this.username = username;
		this.pwd = pwd;
		this.remotepath = remotepath;
	}

	public FTPClient getFtpclient() {
		return ftpclient;
	}

	public void setFtpclient(FTPClient ftpclient) {
		this.ftpclient = ftpclient;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPwd() {
		return pwd;
	}

	public void setPwd(String pwd) {
		this.pwd = pwd;
	}

	public String getRemotepath() {
		return remotepath;
	}

	public void setRemotepath(String remotepath) {
		this.remotepath = remotepath;
	}

	public static void main(String[] args) {

		String fileName = "10210003570000_20161101_1.xls";
		String local_path = "D:/ftp/";
		String address =  "uisftp.chinaums.com";  //"116.228.21.170";
		int ftp_port=21;
		String username = "10210003570000";
		String password = "yuanqi123";
		String remotePath="/build";

		String filename = fileName;
		File file=new File(local_path, filename);
		System.out.println("连接ftp取数据:{ftp_ip:"+address+",ftp_port:"+ftp_port+",ftp_remotepath:"+remotePath+"}");
		System.out.println("FTP账号信息:{username:"+username+",pwd:"+password+"}");
		boolean download = new FtpUtil(address, 21, username, password, remotePath).downFile(file);
		System.out.println(download);
	}

	private boolean login(){
		boolean flag = false;
		if(null == ftpclient){
			ftpclient  = new FTPClient();
		}
		try {
			ftpclient.connect(address, port);
			flag =ftpclient.login(username, pwd);		
		} catch (SocketException e) {
			LOG.addError("连接ftp异常01"+e);
			return false;
		} catch (IOException e) {
			LOG.addError("连接ftp异常02"+e);
			return false;
		}


		return flag;
	}

	public boolean  downFile(File file){
		boolean flag = login();
		Boolean downflag = false;
		try {
			if(flag){
				boolean filetypeflag = 	ftpclient.setFileType(FTPClient.BINARY_FILE_TYPE);
				LOG.addDebug("设置文件类型"+filetypeflag);

				ftpclient.setControlEncoding("GBK");
				//设置文件流传输
				ftpclient.setFileTransferMode(FTPClient.STREAM_TRANSFER_MODE);
				//设置缓冲ftpclient
				ftpclient.setBufferSize(1024);
			
				//设置linux环境
				FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_UNIX);
				conf.setServerLanguageCode("zh");
				ftpclient.configure(conf);

				//判断是否连接成功
				int reply = ftpclient.getReplyCode();
				if (!FTPReply.isPositiveCompletion(reply)){
					ftpclient.disconnect();
					LOG.addError("FTP server refused connection.");
					return false;
				}

				//设置访问被动模式
				ftpclient.setRemoteVerificationEnabled(false);
				ftpclient.enterLocalPassiveMode();

				//ftpclient.changeWorkingDirectory("/");
				if(!"/".equals(remotepath) && !"//".equals(remotepath) && !"\\".equals(remotepath)){
					LOG.addDebug("FTP设置目录" + remotepath);
					ftpclient.changeWorkingDirectory(remotepath);
				}
				FTPFile[] fs=	ftpclient.listFiles();
				if(null==fs || fs.length ==0){
					LOG.addError("ftp上未找到任何文件");
					return false;
				}
				for (FTPFile ff :fs) {
					String name =  ff.getName();
					LOG.addDebug(name);
					if(file.getName().equalsIgnoreCase(name)){
						if(!file.getParentFile().exists()){
							file.getParentFile().mkdirs();
						}
						downflag= true;
						
					
						OutputStream out = new BufferedOutputStream(new FileOutputStream(file));
						ftpclient.retrieveFile(new String(name.getBytes("GBK"),"ISO-8859-1"), out);
						out.flush();
						out.close();
					}
				}
				ftpclient.logout();
			}else{
				LOG.addError("ftp连接失败");
				return false;
			}

		} catch (IOException e) {
			LOG.addError(e);
			return false;
		}finally{
			if(ftpclient.isConnected()){
				try {
					ftpclient.disconnect();
				} catch (IOException e) {
					LOG.addError("finally关闭ftp连接异常"+e);
				}
			}
		}
		return downflag;

	}

	public boolean  downFileFromWindows(File file){
		boolean flag = login();
		Boolean downflag = false;
		try {
			if(flag){
				boolean filetypeflag = 	ftpclient.setFileType(FTPClient.BINARY_FILE_TYPE);
				LOG.addDebug("设置文件类型"+filetypeflag);

				ftpclient.setControlEncoding("GBK");
				//设置文件流传输
				ftpclient.setFileTransferMode(FTPClient.STREAM_TRANSFER_MODE);
				//设置缓冲ftpclient
				ftpclient.setBufferSize(1024);

				//判断是否连接成功
				int reply = ftpclient.getReplyCode();
				if (!FTPReply.isPositiveCompletion(reply)){
					ftpclient.disconnect();
					LOG.addError("FTP server refused connection.");
					return false;
				}

				//设置访问被动模式
				ftpclient.setRemoteVerificationEnabled(false);
				ftpclient.enterLocalPassiveMode();

				//ftpclient.changeWorkingDirectory("/");
				if(!"/".equals(remotepath) && !"//".equals(remotepath) && !"\\".equals(remotepath)){
					ftpclient.changeWorkingDirectory(remotepath);
				}
				FTPFile[] fs=ftpclient.listFiles();
				LOG.addInfo(fs+"");
				if(null==fs || fs.length ==0){
					LOG.addError("ftp上未找到任何文件");
					return false;
				}
				for (FTPFile ff :fs) {
					if(file.getName().equalsIgnoreCase(ff.getName())){
						if(!file.getParentFile().exists()){
							file.getParentFile().mkdirs();
						}
						downflag= true;
						String name =  ff.getName();
						OutputStream out = new BufferedOutputStream(new FileOutputStream(file));
						ftpclient.retrieveFile(new String(name.getBytes("GBK"),"ISO-8859-1"), out);
						out.flush();
						out.close();
					}
				}
				ftpclient.logout();
			}else{
				LOG.addError("ftp连接失败");
				return false;
			}

		} catch (IOException e) {
			LOG.addError(e);
			return false;
		}finally{
			if(ftpclient.isConnected()){
				try {
					ftpclient.disconnect();
				} catch (IOException e) {
					LOG.addError("finally关闭ftp连接异常"+e);
				}
			}
		}
		return downflag;

	}
	
	

}
